import React from 'react'
import Admin from "../../layout/Admin";
import SellerModel from "../../model/seller";
import {formLayout, formTailLayout, getBase64, log} from "../quotation/quotation";
import {Button, Form, Input, InputNumber, Modal, Popover, Table, Upload} from "antd";
import PaginationFooter from "../../component/PaginationFooter/PaginationFooter";
import {CloseCircleOutlined, UploadOutlined} from "@ant-design/icons";
import Info from "../../service/info";

class Seller extends React.Component {
    constructor(props) {
        super(props)
        this.model = new SellerModel()
        this.state = {
            list: [],
            p: 0,
            modal: {
                add: false,
                preview: false,
            },
            previewImage: null,
            previewTitle: '',
            edit: false,
            editValue: null,
            imgs: [],
        }
        this.columns = [
            // Id: 178
            {
                dataIndex: 'Id',
                title: 'Id',
            },
            {
                dataIndex: 'Pinpai',
                title: '品牌',
            },
            {
                dataIndex: 'Name',
                title: '姓名',
            },
            {
                dataIndex: 'Phone',
                title: '手机号码',
            },
            {
                dataIndex: 'Hot',
                title: '热度',
            },
            {
                dataIndex: 'Imgs',
                title: '详情图',
                render: (imgs, record) => {
                    // log(imgs)
                    if (imgs && imgs.length > 0) {
                        return <Popover
                            title='详情图'
                            trigger='click'
                            content={<div>
                                {imgs && imgs.map((img, index) => <img src={img} key={index} alt='' style={{width: 200,}}/>)}
                            </div>}
                        >
                            <a>查看</a>
                        </Popover>
                    } else {
                        return <a onClick={() => this.callEdit(record)}>添加</a>
                    }
                }
            },
            {
                title: '操作',
                render: (recode) => {
                    return <div className='action-links'>
                        <a
                            onClick={() => this.callEdit(recode)}
                        >编辑</a>
                        <a
                            onClick={() => this.delete(recode)}
                        >删除</a>
                    </div>
                }
            },
        ]
    }

    componentDidMount() {
        this.all()
    }

    all = () => {
        const params = {
            P: this.state.p, //      int
            // Id: 0, //     int
            // Name: '', //  string
            // Phone: '', //  string
            // Pinpai: '', // string
            // Hot: 0, //   int
        }
        this.model
            .all(params)
            .then(res => {
                const code = res.data.code
                if (code === 0) {
                    const data = res.data.data
                    log('all,', data)
                    this.setState({
                        list: data.saler,
                    })
                }
            })
    }

    delete = (record) => {
        log(record)
        this.model
            .delete({
                Id: record.Id,
            })
            .then(res => {
                const code = res.data.code
                if (code === 0) {
                    Info.success('删除成功')
                    this.all()
                } else {
                    Info.error(res.data.error())
                }
            })
    }


    onAdd = (value) => {
        value.Imgs = this.state.imgs
        // value.Detailimgs = this.state.detailImgs
        if (this.state.edit) {
            value = {
                ...this.state.editValue,
                ...value,
            }
            value.Id = this.state.editValue.Id
            const imgs = this.state.editValue.Imgs
            if (imgs) {
                value.Imgs = [...this.state.editValue.Imgs, ...this.state.imgs,]
            }

        }
        log(value)
        this.model
            .add(value)
            .then(res => {
                if (res.data.code === 0) {
                    Info.success('上传/编辑成功')
                    this.addForm && this.addForm.resetFields()
                    this.cancelModal('add')
                    this.setState({
                        imgs: [],
                        detailImgs: [],
                        edit: false,
                        add: false,
                    })
                    this.all()
                } else {
                    Info.warning(res.data.err)
                }
            })
    }

    callEdit = (record) => {
        this.callModal('add')
        this.setState({
            editValue: record,
            edit: true,
        })

        setTimeout(() => {
            this.addForm.setFieldsValue({
                ...record,
            })
        }, 0)
    }


    prevPage = () => {
        this.setState({
            p: this.state.p - 1,
        }, () => this.all())
    }

    nextPage = () => {
        this.setState({
            p: this.state.p + 1,
        }, () => this.all())
    }

    callModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal(key) {
        this.setState({
            ...this.state,
            modal: {
                ...this.state.modal,
                [key]: false
            }
        })
    }

    onAddFormCancel = () => {
        this.cancelModal('add')
        this.addForm.resetFields()
        this.setState({
            edit: false,
            imgs: [],
        })
    }

    deleteEditImage = (index, name) => {
        const imgs = this.state.editValue[name]
        imgs.splice(index, 1)
        this.setState({
            editValue: {
                ...this.state.editValue,
                [name]: imgs,
            }
        })
    }

    uploadInputProps = (name) => {

        const fileList = this.state[name]

        return {

            onRemove: file => {
                this.setState(state => {
                    const index = state[name].indexOf(file);
                    const newFileList = state[name].slice();
                    newFileList.splice(index, 1);
                    return {
                        [name]: newFileList,
                    }
                })
            },

            beforeUpload: () => false,

            onChange: ({fileList,}) => {
                this.setState({
                    [name]: fileList,
                })
            },

            onPreview: async (file) => {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj);
                }

                this.setState({
                    previewImage: file.url || file.preview,
                    previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
                }, () => this.callModal('preview'));
            },

            fileList,
        }

    }


    render() {
        return (
            <>
                <Modal
                    visible={this.state.modal.preview}
                    title={this.state.previewTitle}
                    footer={null}
                    onCancel={() => this.cancelModal('preview')}
                >
                    <img alt="example" style={{ width: '100%' }} src={this.state.previewImage} />
                </Modal>
                <Modal
                    visible={this.state.modal.add}
                    onCancel={this.onAddFormCancel}
                    footer={null}
                    title={'销售人员表单'}
                    width='80%'
                >
                    <Form
                        {...formLayout}
                        name='add'
                        ref={el => this.addForm = el}
                        onFinish={this.onAdd}
                    >
                        {/*Name   string*/}
                        <Form.Item
                            label="姓名"
                            name="Name"
                        >
                            <Input placeholder='请输入姓名'/>
                        </Form.Item>
                        {/*Phone  string*/}
                        <Form.Item
                            label="手机号码"
                            name="Phone"
                        >
                            <Input placeholder='请输入手机号码'/>
                        </Form.Item>
                        {/*Pinpai string*/}
                        <Form.Item
                            label="品牌"
                            name="Pinpai"
                        >
                            <Input placeholder='请输入品牌'/>
                        </Form.Item>
                        {/*Hot    int*/}
                        <Form.Item
                            label="热度"
                            name="Hot"
                        >
                            <InputNumber placeholder='请输入热度'/>
                        </Form.Item>
                        {/*Imgs   string*/}
                        {(this.state.edit) && this.state.editValue.Imgs && <Form.Item
                            label='详情图片'
                        >
                            {this.state.editValue.Imgs.map((src, index) => {
                                return <div
                                    key={index}
                                    style={{position: 'relative', display: 'inline-block'}}
                                >
                                    <img src={src} alt='' style={{width: 200}}/>
                                    <CloseCircleOutlined
                                        style={{position: 'absolute', top: 0, right: 0,}}
                                        onClick={() => {
                                            this.deleteEditImage(index, 'Imgs')
                                        }}
                                    />
                                </div>
                            })}
                        </Form.Item>}
                        <Form.Item
                            label="上传详情图片"
                        >
                            <Upload
                                listType="picture-card"
                                fileList={this.state.imgs}
                                {...this.uploadInputProps('imgs')}
                                multiple={true}
                            >
                                <Button icon={<UploadOutlined />}>上传详情图片</Button>
                            </Upload>
                        </Form.Item>
                        <Form.Item {...formTailLayout}>

                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>

                        </Form.Item>

                    </Form>
                </Modal>
                <Admin>
                    <div className='list-container'>
                        <div style={{marginBottom: '8px'}}>
                            <Button
                                onClick={() => this.callModal('add')}
                            >
                                添加销售人员
                            </Button>
                        </div>
                        <Table
                            dataSource={this.state.list}
                            columns={this.columns}
                            pagination={false}
                            rowKey={(record, index) => index}
                        />
                        <PaginationFooter
                            pageIndex={this.state.p}
                            prevPage={this.prevPage}
                            nextPage={this.nextPage}
                        />
                    </div>

                </Admin>
            </>

        )
    }
}

export default Seller